<?php
/***
 * 产品模板后台 Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Services\ProductTempService;

use App\Services\BrandService\BrandToolService;
use App\Services\ColourService\ColourTool;
use App\Services\CrowdService\CrowdService;
use App\Services\CrowdService\CrowdTool;
use App\Services\ImgServices\ImgTool;
use App\Services\ModifyResourcePriceRecordsService\ModifyResourcePriceRecordsService;
use App\Services\ProdTempCategoryService\ProdTempCategoryTool;
use App\Services\TagService\TagService;
use App\Services\TagService\TagTool;
use App\Services\Tool\GeneralTool;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use  Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductTempService
{
    protected  $crowdService;
    protected  $imgTool;
    protected  $tagService;
    protected  $productTempTool;
    protected   $tool;
    const        EXCEL_EXT=['xls','xlsx'];
    /**
     * ProductTempService constructor.
     */
    public function __construct(CrowdService $crowdService,
                                TagService $tagService,
                                GeneralTool $tool,
                                ProductTempTool $productTempTool,
                                ImgTool $imgTool)
    {
        $this->crowdService=$crowdService;
        $this->imgTool=$imgTool;
        $this->tagService=$tagService;
        $this->productTempTool=$productTempTool;
        $this->tool=$tool;
    }

    /***
     * 保存产品模板
     * @param array $data
     * @return bool
     */
    public function addProdTemp(array $data){
        try{

            $product_temp_id=GeneralTool::only_no();
            $crowd_ids=array_unique($data['crowd_ids']);
            $colour_ids=array_unique($data['colour_ids']);
            $attributes=array_unique($data['attributes']);
            $sizes=array_unique($data['sizes']);
            $has_size=$data['has_size'];
            $default_stock=$data['default_stock'];
            $default_price=$data['default_price'];
            unset($data['crowd_ids']);
            unset($data['colour_ids']);
            unset($data['sizes']);
            unset($data['attributes']);
            DB::beginTransaction();
            foreach ($crowd_ids as $crowd_id){
                $crowd_name=$this->crowdService->getCrowdNameById($crowd_id);
                if(!empty($crowd_name)){
                    $temp_crowd['crowd_name']=$crowd_name;
                    $temp_crowd['crowd_id']=$crowd_id;
                    $temp_crowd['product_temp_id']=$product_temp_id;
                    $this->saveProductTempCrowd($temp_crowd);
                }
            }
            foreach ($colour_ids as $colour_id){
                $temp_colour['colour_id']=$colour_id;
                $temp_colour['original_price']=$default_price;
                $temp_colour['product_temp_id']=$product_temp_id;
                $this->saveProductTempColour($temp_colour);
            }
            if($has_size===0){
                $temp_size['size_name']='通用';
                $temp_size['product_temp_id']=$product_temp_id;
                $temp_size['size_values']='';
                $this->saveProductTempSize($temp_size);
            }else{
                foreach ($sizes as $size){
                    $temp_size['size_name']=$size;
                    $temp_size['product_temp_id']=$product_temp_id;
                    $temp_size['size_values']='';
                    $this->saveProductTempSize($temp_size);
                }
            }
            foreach ($attributes as $attribute){
                $attribute_arr=explode('_',$attribute);
                if(sizeof($attribute_arr)!=4){
                    continue;
                }
                $temp_attr['attr_id']=intval($attribute_arr[1]);
                $temp_attr['attr_name']=$attribute_arr[2];
                $temp_attr['attr_value']=$attribute_arr[3];
                $temp_attr['product_temp_id']=$product_temp_id;
                $this->saveProductTempAttribute($temp_attr);
            }
            $temp_colour_ids=ProductTempTool::productTempColourIdsByProductTempId($product_temp_id,1);
            $temp_size_names=ProductTempTool::productTempSizeNamesByProductTempId($product_temp_id,1);;
            foreach ($temp_colour_ids as $temp_colour_id){
                $temp_colour_name=ColourTool::getColourNameByColourId($temp_colour_id);
                $temp_stock=array();
                $temp_stock['product_temp_id']=$product_temp_id;
                $temp_stock['colour_name']=$temp_colour_name;
                $temp_stock['colour_id']=$temp_colour_id;
                $temp_stock['stock']=$default_stock;
                $temp_stock['trading_status']=1;
                $temp_stock['created_at']=time();
                $temp_stock['updated_at']=time();
                foreach ($temp_size_names as $temp_size_name){
                    $temp_stock['size_name']=$temp_size_name;
                    DB::table('product_temp_stocks')->insert($temp_stock);
                }
            }
            $time=time();
            $data['product_temp_id']=$product_temp_id;
            $data['created_at']=$time;
            $data['updated_at']=$time;
            $data['state']=1;
            $res=DB::table('product_temps')->insert($data);
            if($res==1){
                //资源Id绑定在所有特殊标签下
             $this->tagService->resourceIdBindingSpecialTag($product_temp_id,2);
            }
            return ($res==1)?true:false;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 产品模板更新
     * @param array $data
     * @return bool
     */
    public function updateProdTemp(array $data){
        try{
            $product_temp_id=$data['product_temp_id'];
            $product_temp_category_id=$data['product_temp_category_id'];
            $crowd_ids=array_unique($data['crowd_ids']);
            $colour_ids=array_unique($data['colour_ids']);
            $attributes=array_unique($data['attributes']);
            $sizes=array_unique($data['sizes']);
            $has_size=$data['has_size'];
            $bluk_update_stock=$data['bluk_update_stock'];
            $default_price=$data['default_price'];
            unset($data['crowd_ids']);
            unset($data['colour_ids']);
            unset($data['sizes']);
            unset($data['attributes']);
            unset($data['bluk_update_stock']);
            DB::beginTransaction();
            $temp_exist_colour_ids=$this->getColourIdsByProductTempId($product_temp_id,1);
            $this->delProductTempCrowdsByProductTempId($product_temp_id);
            $this->delProductTempSizesByProductTempId($product_temp_id);
            $this->delProductTempAttrMapsByProductTempId($product_temp_id);
            $this->delProductTempColour($product_temp_id);
            $this->delProductTempStocksByProductTempId($product_temp_id);//删除库存
            $old_product_temp=ProductTempTool::getProductTempByProductTempId($product_temp_id,1);
            if(empty($old_product_temp)){
                return false;
            }
            foreach ($crowd_ids as $crowd_id){
                $crowd_name=CrowdTool::crowdNameByCrowdId($crowd_id);
                if(!empty($crowd_name)){
                    $temp_crowd['crowd_name']=$crowd_name;
                    $temp_crowd['crowd_id']=$crowd_id;
                    $temp_crowd['product_temp_id']=$product_temp_id;
                    $temp_crowd_exist=$this->productTempCrowdExist($product_temp_id,$crowd_id,0);
                    if($temp_crowd_exist){
                        $this->updateProductTempCrowd($temp_crowd);
                    }else{
                        $this->saveProductTempCrowd($temp_crowd);
                    }
                }
            }
            foreach ($colour_ids as $colour_id){
                $temp_colour=array();
                $temp_colour['colour_id']=$colour_id;
                $temp_colour['product_temp_id']=$product_temp_id;
                $temp_colour_exist=$this->productTempColourExist($product_temp_id,$colour_id,0);
                if($temp_colour_exist===false){
                    $temp_colour['original_price']=$default_price;
                    $this->saveProductTempColour($temp_colour);
                }else{
                    //有新增颜色
                    $colour_id_in_arr=in_array($colour_id,$temp_exist_colour_ids);
                    if(!$colour_id_in_arr){
                        $temp_colour['original_price']=$default_price;
                        ModifyResourcePriceRecordsService::delete($product_temp_id,$colour_id,2);
                    }
                    //删除定时修改定价
                    $this->updateProductTempColour($temp_colour);
                }
            }
            if($has_size===0){
                $temp_size['size_name']='通用';
                $temp_size['product_temp_id']=$product_temp_id;
                $temp_size['size_values']='';
                $temp_size_exist=$this->productTempSizeExist($product_temp_id,'通用',0);
                if(!$temp_size_exist){
                    $temp_size['size_values']='';
                    $this->saveProductTempSize($temp_size);
                }else{
                    $this->updateProductTempSize($temp_size);
                }
            }else{
                foreach ($sizes as $size){
                    $temp_size['size_name']=$size;
                    $temp_size['product_temp_id']=$product_temp_id;
                    $temp_size_exist=$this->productTempSizeExist($product_temp_id,$size,0);
                    if(!$temp_size_exist){
                        $temp_size['size_values']='';
                        $this->saveProductTempSize($temp_size);
                    }else{
                        $this->updateProductTempSize($temp_size);
                    }
                }
            }
            foreach ($attributes as $attribute){
                $attribute_arr=explode('_',$attribute);
                if(sizeof($attribute_arr)!=4){
                    continue;
                }
                $temp_attr['attr_id']=intval($attribute_arr[1]);
                $temp_attr['attr_name']=$attribute_arr[2];
                $temp_attr['attr_value']=$attribute_arr[3];
                $temp_attr['product_temp_id']=$product_temp_id;
                $temp_attr['category_id']=$product_temp_category_id;
                $temp_attr_exist=$this->productTempAttrExist($product_temp_id,$temp_attr['attr_id'],0);
                if(!$temp_attr_exist){
                    $this->saveProductTempAttribute($temp_attr);
                }else{
                    $this->updateProductTempAttribute($temp_attr);
                }
            }
            $temp_colour_ids=ProductTempTool::productTempColourIdsByProductTempId($product_temp_id,1);
            $temp_size_names=ProductTempTool::productTempSizeNamesByProductTempId($product_temp_id,1);
            foreach ($temp_colour_ids as $temp_colour_id){
                $temp_colour_name=ColourTool::getColourNameByColourId($temp_colour_id);
                $temp_stock=array();
                $temp_stock['product_temp_id']=$product_temp_id;
                $temp_stock['colour_name']=$temp_colour_name;
                $temp_stock['colour_id']=$temp_colour_id;
                $temp_stock['state']=1;
                $temp_stock['updated_at']=time();
                if($bluk_update_stock===1){
                    $temp_stock['stock']=$data['default_stock'];
                }else{
                    $temp_colour['stock']=$old_product_temp->default_stock;
                }
                foreach ($temp_size_names as $temp_size_name){
                    $id=DB::table('product_temp_stocks')
                        ->where(array(
                            'product_temp_id'=>$product_temp_id,
                            'colour_id'=>$temp_colour_id,
                            'size_name'=>$temp_size_name))
                        ->value('id');
                    if(!empty($id)){
                        DB::table('product_temp_stocks')
                            ->where(array('id'=>$id))
                            ->update($temp_stock);
                    }else{
                        $temp_stock['trading_status']=1;
                        $temp_stock['created_at']=time();
                        $temp_stock['size_name']=$temp_size_name;
                        DB::table('product_temp_stocks')->insert($temp_stock);
                    }
                }
            }
            $time=time();
            $data['product_temp_id']=$product_temp_id;
            $data['updated_at']=$time;
            $data['state']=1;
            $res=DB::table('product_temps')->where(array('product_temp_id'=>$product_temp_id))
                ->update($data);
            return ($res===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    /***
     * 保存产品模板人群属性
     * @param array $data
     * @return mixed
     */
     private function saveProductTempCrowd(array $data){
         $data['created_at']=time();
         $data['updated_at']=time();
         return DB::table('product_temp_crowds')->insert($data);
     }
    private function updateProductTempCrowd(array $data){
        $data['updated_at']=time();
        $product_temp_id=$data['product_temp_id'];
        $crowd_id=$data['crowd_id'];
        $data['state']=1;
        $res=DB::table('product_temp_crowds')
            ->where(array('crowd_id'=>$crowd_id,'product_temp_id'=>$product_temp_id))
            ->update($data);
        return $res;
    }
    /***
     * 删除产品模板下的人群
     * @param $product_temp_id
     * @return mixed
     */
    private function delProductTempCrowd($product_temp_id){
        $res=DB::table('product_temp_crowds')->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
        ->update(array(
            'updated_at'=>time(),
            'state'=>0,
        ));
        return $res;
    }

    /***
     * 删除产品模板下的颜色映射
     * @param $product_temp_id
     * @return mixed
     */
    private function delProductTempColour($product_temp_id){
        $res=DB::table('product_temp_colours')->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
            ->update(array(
                'updated_at'=>time(),
                'state'=>0,
            ));
        return $res;
    }

    /***
     * 判断某一模板下的具体颜色是不是存在
     * @param $product_temp_id
     * @param $colour_id
     * @return bool
     */
    public function productTempColourExist($product_temp_id,$colour_id,$state=1){
        if(empty($product_temp_id)||empty($colour_id)){
            return false;
        }
        if($state===1){
            $num=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id,'state'=>1))
                ->count();
        }else{
            $num=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id))
                ->count();
        }
        return ($num==0)?false:true;
    }

    /***
     * 获取模板下有的颜色数组
     * @param $product_temp_id
     * @param int $state
     * @return array
     */
    public function getColourIdsByProductTempId($product_temp_id,$state=1){
        if(empty($product_temp_id)){
            return array();
        }
        $query=DB::table('product_temp_colours')
            ->where(array('product_temp_id'=>$product_temp_id));
        if($state===1){
           $query->where('state',1);
        }
        $colour_ids=$query->pluck('colour_id')->toArray();
        return empty($colour_ids)?array():$colour_ids;
    }
    public function productTempColourByProdTempIdAndColour($product_temp_id,$colour_id,$state=1){
        if(empty($product_temp_id)||empty($colour_id)){
            return false;
        }
        if($state===1){
            $temp_colour=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id,'state'=>1))
                ->first();
        }else{
            $temp_colour=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id))
                ->first();
        }
        return $temp_colour;
    }
    public function getProductTempCustomZoneList($product_temp_id,$colour_id){
        if(empty($product_temp_id)||empty($colour_id)){
            return false;
        }
        $product_temp_colour=DB::table('product_temp_colours')
            ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id,'state'=>1))
            ->first();
        if(empty($product_temp_colour)){
            return false;
        }
        $temp_custom_zones=DB::table('product_temp_custom_zones')
            ->where(array('product_temp_id'=>$product_temp_id,'prod_temp_colour_id'=>$product_temp_colour->id,'state'=>1))
            ->get()
             ->toArray();
        return array('temp_custom_zones'=>$temp_custom_zones,'temp_colour'=>$product_temp_colour);
    }

    /***
     * 定制区域下的工艺列表
     * @param $temp_custom_zone_id
     * @return array
     */
    public function getProductTempCraftsmanshipListByCustomZoneId($temp_custom_zone_id){
        if(empty($temp_custom_zone_id)){
            return array();
        }
        $temp_craftsmanships=DB::table('product_temp_craftsmanships')
            ->where(array('temp_custom_zone_id'=>$temp_custom_zone_id,'state'=>1))
            ->get()
            ->toArray();
        return empty($temp_craftsmanships)?array():$temp_craftsmanships;
    }

    /***
     * 获取模板下对应颜色
     * @param $product_temp_id
     * @param $colour_id
     * @param int $state
     * @return null
     */
    public function getProductTempColourByProductTempIdAndColour($product_temp_id,$colour_id,$state=1){
        if(empty($product_temp_id)||empty($colour_id)){
            return null;
        }
        $query=DB::table('product_temp_colours')
            ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id));
        if($state===1){
            $query->where('state',1);
        }
        $product_temp_colour=$query->first();
        return $product_temp_colour;
    }
    /***
     * 获取制作区域已经使用到的工艺
     * @param $temp_custom_zone_id
     * @param int $state
     * @return array
     */
    public function getProductTempCraftsmanshipTypesByCustomZoneId($temp_custom_zone_id,$state=1){
        if(empty($temp_custom_zone_id)){
            return array();
        }
        $query=DB::table('product_temp_craftsmanships')
            ->where(array('temp_custom_zone_id'=>$temp_custom_zone_id));
        if($state===1){
            $query->where('state',1);
        }
        $query->pluck('craftsmanship_type')
            ->toArray();
        return empty($craftsmanship_types)?array():$craftsmanship_types;
    }
    /***
     * 产品创作区域位置类型列表
     * @param $temp_category_id
     * @return array
     */
    public function getProductTempCustomZonePositions($temp_category_id){
        if(empty($temp_category_id)){
            return array();
        }
        $temp_custom_zone_positions=DB::table('product_temp_custom_zone_positions')
            ->where(array('temp_category_id'=>$temp_category_id,'state'=>1))
            ->select('position_type','position_name','temp_category_id')
            ->get()
            ->toArray();
        return empty($temp_custom_zone_positions)?array():$temp_custom_zone_positions;
    }

    /***
     * 获取设计区域信息
     * @param $id
     * @return null
     */
    public function getProductTempCustomZoneById($id){
        if(empty($id)){
            return null;
        }
        $temp_custom_zone=DB::table('product_temp_custom_zones')
            ->where(array('id'=>$id,'state'=>1))
            ->first();
        return $temp_custom_zone;
    }

    /***
     * 保存制作工艺
     * @param array $data
     * @return bool
     */
    public function saveCraftsmanship(array $data){
       try{
           $data['state']=1;
           $data['updated_at']=time();
           $craftsmanship_type= $data['craftsmanship_type'];
           $data['craftsmanship_name']=ProductTempTool::getCraftsmanshipNameByCraftsmanshipId($data['craftsmanship_type']);
           $custom_zone_id= $data['temp_custom_zone_id'];
           $craftsmanship_exist=ProductTempTool::craftsmanshipExistByCraftsmanshipTypeAndZoneId($craftsmanship_type,$custom_zone_id,0);
           if($craftsmanship_exist){
               $res=DB::table('product_temp_craftsmanships')
                   ->where(array('temp_custom_zone_id'=>$custom_zone_id,'craftsmanship_type'=>$craftsmanship_type))
                   ->update($data);
           }else{
               $data['created_at']=time();
               $res=DB::table('product_temp_craftsmanships')
                   ->insert($data);
           }
           //为工艺添加默认配色
           if($res>0){
               $temp_craftsmanship_id=DB::table('product_temp_craftsmanships')
                   ->where(array('temp_custom_zone_id'=>$custom_zone_id,'craftsmanship_type'=>$craftsmanship_type,'state'=>1))
                   ->value("id");
               if(!empty($temp_craftsmanship_id)){
                   $this->addCraftsmanshipDefaultColourByCraftsmanshipId($temp_craftsmanship_id);
               }
           }
           return ($res===0)?false:true;
       }catch (\Exception $e){
            Log::info($e);
            return false;
       }
    }
    /***
     * ID判断产品模板某颜色是不是存在
     * @param $id
     * @return bool
     */
    public function productTempColourExistById($id,$state=0){
        if(empty($id)||empty($id)){
            return false;
        }
        if($state===1){
            $num=DB::table('product_temp_colours')
                ->where(array('id'=>$id,'state'=>1))
                ->count();
        }else{
            $num=DB::table('product_temp_colours')
                ->where(array('id'=>$id))
                ->count();
        }
        return ($num==0)?false:true;
    }

    /***
     * 更新价格
     * @param $id
     * @param $price
     * @return bool
     */
    public function productTempColourUpdatePrice($id,$price){
        if(empty($id)||($price===null)){
            return false;
        }
        $num=DB::table('product_temp_colours')
            ->where(array('id'=>$id))
            ->update(array(
                'original_price'=>$price,
                'updated_at'=>time()
            ));
        return ($num==1)?true:false;
    }

    /***
     * id 获取$product_temp_colour
     * @param $id
     * @param int $state
     * @return null
     */
    public function getProductTempColourByProductTempColourId($id,$state=1){
        if(empty($id)){
            return null;
        }
        $query=DB::table('product_temp_colours')
            ->where(array('id'=>$id));
        if($state===1){
            $query->where('state',1);
        }
        $product_temp_colour=$query->first();
        return $product_temp_colour;
    }
    /***
     * 修改产品模板颜色排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public function productTempColourUpdateSort($id,$sort){
        if(empty($id)||(empty($sort))){
            return false;
        }
        $num=DB::table('product_temp_colours')
            ->where(array('id'=>$id))
            ->update(array(
                'sort'=>$sort,
                'updated_at'=>time()
            ));
        return ($num==1)?true:false;
    }

    /***
     * 获取产品模板库存
     * @param $product_temp_colour_id
     * @return array|bool
     */
    public function prodTempStockByColour($product_temp_id,$product_temp_colour_id){
        if(empty($product_temp_colour_id)||empty($product_temp_id)){
            return false;
        }
        $colour_id=DB::table('product_temp_colours')
            ->where(array('id'=>$product_temp_colour_id,'state'=>1))
            ->value('colour_id');
        if(empty($colour_id)){
            return false;
        }
        $temp_size_names=ProductTempTool::getProdTempSizesByProdTempId($product_temp_id);
        $temp_size_names=empty($temp_size_names)?array():$temp_size_names;
        $temp_stocks=array();
        foreach ($temp_size_names as $temp_size_name){
          $temp_stock['size']=$temp_size_name;
          $temp_stock['temp_stock_id']=0;
          $temp_stock['stock']=0;
          $temp_stock['actual_stock']=0;
          $temp_stock['sku']='';
          $temp_stock['colour_id']=$colour_id;
          $temp_stock['product_temp_id']=$product_temp_id;
          $colour_name=ColourTool::getColourNameByColourId($colour_id);
          if(empty($colour_name)) {
              $temp_stocks[]=(object)$temp_stock;
              continue;
          }
          $temp_stock_info=ProductTempTool::getProdTempStockInfo($product_temp_id,$colour_name,$temp_size_name,1);
          if(!empty($temp_stock_info)){
              $temp_stock['temp_stock_id']=$temp_stock_info->id;
              $temp_stock['stock']=$temp_stock_info->stock;
              $temp_stock['sku']=$temp_stock_info->sku;
              $temp_stock['actual_stock']=$temp_stock_info->actual_stock;
          }
            $temp_stocks[]=(object)$temp_stock;
        }
        return $temp_stocks;
    }

    /***
     * 保存产品模板虚拟库存
     * @param $stock
     * @param $size_name
     * @param $colour_id
     * @param $temp_id
     * @return bool
     */
    public function saveProductTempStock($stock,$size_name,$colour_id,$temp_id){
        if(($stock===null)){
            return false;
        }
        $data=array(
            'size_name'=>$size_name,
            'colour_id'=>$colour_id,
            'product_temp_id'=>$temp_id
        );
        $id=DB::table('product_temp_stocks')->where($data)->value('id');
        $data['state']=1;
        $data['stock']=$stock;
        $data['colour_name']=ColourTool::getColourNameByColourId($colour_id);
        $data['updated_at']=time();
        if(empty($id)){
            $res=DB::table('product_temp_stocks')
                ->insert($data);
        }else{
            $data['created_at']=time();
            $res=DB::table('product_temp_stocks')
                ->where(array('id'=>$id))
                ->update($data);
        }

        return ($res===0)?false:true;
    }

    /***
     * 保存产品模板实际库存
     * @param $actual_stock
     * @param $size_name
     * @param $colour_id
     * @param $temp_id
     * @return bool
     */
    public function saveProductTempActualStock($actual_stock,$size_name,$colour_id,$temp_id){
        if(($actual_stock===null)){
            return false;
        }
        $data=array(
            'size_name'=>$size_name,
            'colour_id'=>$colour_id,
            'product_temp_id'=>$temp_id
        );
        $id=DB::table('product_temp_stocks')->where($data)->value('id');
        $data['state']=1;
        $data['actual_stock']=$actual_stock;
        $data['colour_name']=ColourTool::getColourNameByColourId($colour_id);
        $data['updated_at']=time();
        if(empty($id)){
            $res=DB::table('product_temp_stocks')
                ->insert($data);
        }else{
            $data['created_at']=time();
            $res=DB::table('product_temp_stocks')
                ->where(array('id'=>$id))
                ->update($data);
        }

        return ($res===0)?false:true;
    }
    /***
     * sku更新
     * @param $temp_stock_id
     * @param $sku
     * @return bool
     */
    public function saveProductTempSku($sku,$size_name,$colour_id,$temp_id){
        if(empty($size_name)||empty($sku)||empty($colour_id)||empty($temp_id)){
            return false;
        }
        $data=array(
            'size_name'=>$size_name,
            'colour_id'=>$colour_id,
            'product_temp_id'=>$temp_id
        );
        $id=DB::table('product_temp_stocks')->where($data)->value('id');
        $data['state']=1;
        $data['sku']=$sku;
        $data['updated_at']=time();
        if(empty($id)){
            $res=DB::table('product_temp_stocks')
                ->insert($data);
        }else{
            $data['created_at']=time();
            $res=DB::table('product_temp_stocks')
                ->where(array('id'=>$id))
                ->update($data);
        }
        return ($res===0)?false:true;
    }
    /***
     * 删除模板对应的某一颜色
     * @param $id
     * @return bool
     */
    public function delProductTempColourById($id){
        try{
            DB::beginTransaction();
            $temp_colour=DB::table('product_temp_colours')
                ->where(array('id'=>$id,'state'=>1))
                ->select('colour_id','product_temp_id')
                ->first();
            if(empty($temp_colour)){
                return false;
            }
            $temp_custom_zones_del_res=DB::table('product_temp_custom_zones')
                ->where(array(
                    'prod_temp_colour_id'=>$id,
                    'state'=>1
                ))->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            $res=DB::table('product_temp_stocks')
                ->where(array(
                    'product_temp_id'=>$temp_colour->product_temp_id,
                    'colour_id'=>$temp_colour->colour_id,
                    'state'=>1
                ))->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            $num=DB::table('product_temp_colours')
                ->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 删除模板定制区域
     * @param $id
     * @return bool
     */
    public function delCustomZone($id){
        try{
            DB::beginTransaction();
            $num=DB::table('product_temp_custom_zones')
                ->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 添加制作工艺时添加对应默认配色
     * @param $temp_craftsmanship_id
     * @return bool
     */
    public function addCraftsmanshipDefaultColourByCraftsmanshipId($temp_craftsmanship_id)
    {
        if(empty($temp_craftsmanship_id)){
            return false;
        }
        $colour_ids=$this->productTempTool->getAllCraftsmanshipDefaultColourIds();
        foreach ($colour_ids as $colour_id){
            $data=array();
            $data['product_temp_craftsmanship_id']=$temp_craftsmanship_id;
            $data['colour_id']=$colour_id;
            $product_temp_craftsmanship_exist=ProductTempTool::productTempCraftsmanshipColourExistByCraftsmanshipIdAndColourId($temp_craftsmanship_id,$colour_id,0);
            if($product_temp_craftsmanship_exist){
                $res=$this->updateTempCraftsmanshipColour($data);
            }else{
                $res=$this->saveTempCraftsmanshipColour($data);
            }
        }
        return true;
    }

    /***
     * 删除模板工艺下默认配色
     * @param $temp_craftsmanship_id
     * @return bool
     */
    public function delCraftsmanshipColourByCraftsmanshipId($temp_craftsmanship_id)
    {
        if(empty($temp_craftsmanship_id)){
            return false;
        }
        $num=DB::table('product_temp_craftsmanship_colours')
            ->where(array('product_temp_craftsmanship_id'=>$temp_craftsmanship_id,'state'=>1))
        ->update(array(
            'state'=>0,
            'updated_at'=>time()
        ));
        return ($num>0)?true:false;
    }
    /***
     * 删除定制区域工艺对应颜色
     * @param $craftsmanship_colour_id
     * @return bool
     */
    public function deleteCraftsmanshipColour($craftsmanship_colour_id){
        if(empty($craftsmanship_colour_id)||!is_int($craftsmanship_colour_id)){
            return false;
        }
        $del_res=DB::table('product_temp_craftsmanship_colours')
            ->where(array('id'=>$craftsmanship_colour_id,'state'=>1))
            ->update(array(
                'state'=>0,
                'updated_at'=>time()
            ));
        return empty($del_res)?false:true;
    }

    /****
     * 删除制作工艺下默认颜色列表下颜色
     * @param $id
     * @return bool
     */
    public function deleteCraftsmanshipDefaultColour($colour_id){
        if(empty($colour_id)||!is_int($colour_id)){
            return false;
        }
        $del_res=DB::table('product_temp_craftsmanship_default_colours')
            ->where(array('colour_id'=>$colour_id,'state'=>1))
            ->update(array(
                'state'=>0,
            ));
        return empty($del_res)?false:true;
    }
    /***
     * 更新定制区域工艺对应颜色排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public  function updateCraftsmanshipColourSort($id,$sort){
        if(empty($id)||!is_int($id)||empty($sort)||!is_int($sort)){
            return false;
        }
        $num=DB::table('product_temp_craftsmanship_colours')
            ->where(array(
                'id'=>$id,
                'state'=>1,
            ))->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return empty($num)?false:true;
    }
    /***
     * 删除定制区域工艺
     * @param $id
     * @return bool
     */
    public function delTempCraftsmanship($id){
        try{
            DB::beginTransaction();
            $num=DB::table('product_temp_craftsmanships')
                ->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            if($num>0){
                $this->delCraftsmanshipColourByCraftsmanshipId($id);
            }
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    public function delProductTemp($id){
        try{
            DB::beginTransaction();
            $product_temp_id=DB::table('product_temps')
                ->where(array('state'=>1,'id'=>$id))
                ->value('product_temp_id');
            if(empty($product_temp_id)){
                return false;
            }
            $this->delProductTempCrowdsByProductTempId($product_temp_id);
            $this->delProductTempSizesByProductTempId($product_temp_id);
            $this->delProductTempAttrMapsByProductTempId($product_temp_id);
            $this->delProductTempCustomZonesByProductTempId($product_temp_id);
            $this->delProductTempStocksByProductTempId($product_temp_id);
            $this->delProductTempSizeFormatsByProductTempId($product_temp_id);
            $num=DB::table('product_temps')
                ->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    public function delProductTempSizesByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_sizes')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempColoursByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempStocksByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_stocks')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempCustomZonesByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_custom_zones')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempCrowdsByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_crowds')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempSizeFormatsByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=DB::table('product_temp_size_formats')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function delProductTempAttrMapsByProductTempId($product_temp_id){
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $num=  DB::table('product_temp_attr_maps')
                ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 获取产品模板下的颜色
     * @param $product_temp_id
     * @return mixed
     */
    public function getProductTempColours($product_temp_id){
        $temp_colours=DB::table('product_temp_colours')
            ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
            ->paginate(10);
        foreach ($temp_colours as $temp_colour){
            $temp_colour->colour_name=ColourTool::getColourNameByColourId($temp_colour->colour_id);
        }
        return $temp_colours;
    }

    /***
     * 获取产品模板属性类型
     * @param $category_id
     * @return mixed
     */
    public function getProductTempAttrs($category_id){
        $query=DB::table('product_temp_attributes')
            ->where(array('state'=>1));
        if(!empty($category_id)&&is_int($category_id)){
            $query->where('category_id',$category_id);
        }else{
            $category_id=0;
        }
        $query->orderBy('updated_at','DESC');
        $temp_attributes=$query->paginate(10);
        $temp_attributes->appends(['category_id' => $category_id])->render();
        return $temp_attributes;
    }
    public function getProductTempSize($product_temp_id){
        $temp_sizes=DB::table('product_temp_sizes')
            ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
            ->paginate(10);
        return $temp_sizes;
    }

    /***
     * 获取尺码详情以及测量方式
     * @param $product_temp_id
     * @return mixed
     */
    public function getProductTempSizeFormat($product_temp_id){
        $temp_size_format=DB::table('product_temp_size_formats')
            ->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
            ->orderBy('updated_at','DESC')
            ->first();
        return $temp_size_format;
    }
    /***
     * 获取产品模板下的一个颜色
     * @param $product_temp_id
     * @param $colour_id
     * @return bool
     */
    public function getProductTempColourByProdTempIdAndColourId($product_temp_id,$colour_id){
        if(empty($product_temp_id)||empty($colour_id)){
            return false;
        }
        $temp_colour=DB::table('product_temp_colours')
            ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id,'state'=>1))
            ->first();
        return $temp_colour;
    }
    /***
     * 查看模板中的具体尺码属性是不是存在
     * @param $product_temp_id
     * @param $size_name
     * @param int $state
     * @return bool
     */
    public function productTempSizeExist($product_temp_id,$size_name,$state=1){
        if(empty($product_temp_id)||empty($size_name)){
            return false;
        }
        if($state===1){
            $num=DB::table('product_temp_sizes')
                ->where(array('product_temp_id'=>$product_temp_id,'size_name'=>$size_name,'state'=>1))
                ->count();
        }else{
            $num=DB::table('product_temp_sizes')
                ->where(array('product_temp_id'=>$product_temp_id,'size_name'=>$size_name))
                ->count();
        }

        return ($num==0)?false:true;
    }

    /***
     * id判断模板尺码详情有没有
     * @param $id
     * @param int $state
     * @return bool
     */
    public function productTempSizeExistById($id,$state=1){
        if(empty($id)){
            return false;
        }
        $query=DB::table('product_temp_sizes')->where(array('id'=>$id));
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num==0)?false:true;
    }
    public function productTempAttrExist($product_temp_id,$attr_id,$state=1){
        if(empty($product_temp_id)||empty($attr_id)){
            return false;
        }
        if($state===1){
            $num=DB::table('product_temp_attr_maps')
                ->where(array('product_temp_id'=>$product_temp_id,'attr_id'=>$attr_id,'state'=>1))
                ->count();
        }else{
            $num=DB::table('product_temp_attr_maps')
                ->where(array('product_temp_id'=>$product_temp_id,'attr_id'=>$attr_id))
                ->count();
        }

        return ($num==0)?false:true;
    }
    /***
     * 查看模板中的人群属性是不是存在
     * @param $product_temp_id
     * @param $crowd_id
     * @param int $state
     * @return bool
     */
    public function productTempCrowdExist($product_temp_id,$crowd_id,$state=1){
        if(empty($product_temp_id)||empty($crowd_id)){
            return false;
        }
        $query=DB::table('product_temp_crowds')
            ->where(array('product_temp_id'=>$product_temp_id,'crowd_id'=>$crowd_id));
        if($state===1){
            $query->where('state',1);

        }
        $num=$query->count();
        return ($num==0)?false:true;
    }
    /***
     * 删除产品模板下的颜色尺码映射
     * @return mixed
     */
    private function delProductTempSize($product_temp_id){
        $res=DB::table('product_temp_sizes')->where(array('product_temp_id'=>$product_temp_id,'state'=>1))
            ->update(array(
                'updated_at'=>time(),
                'state'=>0,
            ));
        return $res;
    }

    /***
     * 删除模板对应尺码
     * @param $id
     * @return bool
     */
    public function delProductTempSizeById($id){
        try{
            $temp_size=DB::table('product_temp_sizes')
                ->where(array('id'=>$id,'state'=>1))
                ->select('product_temp_id','size_name')
                ->first();
            if(empty($temp_size)){
                return false;
            }
            DB::beginTransaction();
            $del_res=$this->delProductTempStocksByTempIdAndSizeName($temp_size->product_temp_id,$temp_size->size_name);
            $res=DB::table('product_temp_sizes')->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'updated_at'=>time(),
                    'state'=>0,
                ));

            return empty($res)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 删除模板对应尺码下的库存
     * @param $product_temp_id
     * @param $size_name
     * @return bool
     */
    public function delProductTempStocksByTempIdAndSizeName($product_temp_id,$size_name){
        $res=DB::table('product_temp_stocks')->where(array('product_temp_id'=>$product_temp_id,'size_name'=>$size_name))
            ->update(array(
                'updated_at'=>time(),
                'state'=>0,
            ));

        return empty($res)?false:true;
    }
    /***
     * 保存产品模板人群颜色属性
     * @param array $data
     * @return mixed
     */
    private function saveProductTempColour(array $data){
        $data['created_at']=time();
        $data['updated_at']=time();
        $data['state']=1;
        return DB::table('product_temp_colours')->insert($data);
    }

    private function updateProductTempColour(array $data){
        $data['updated_at']=time();
        $product_temp_id=$data['product_temp_id'];
        $colour_id=$data['colour_id'];
        $data['state']=1;
        $res=DB::table('product_temp_colours')
            ->where(array('colour_id'=>$colour_id,'product_temp_id'=>$product_temp_id))
            ->update($data);
        return $res;
    }
    /***
     * 保存产品模板人群尺码
     * @param array $data
     * @return mixed
     */
    private function saveProductTempSize(array $data){
        $data['created_at']=time();
        $data['updated_at']=time();
        $data['state']=1;
        return DB::table('product_temp_sizes')->insert($data);
    }

    /***
     * 更新
     * @param array $data
     * @return mixed
     */
    private function updateProductTempSize(array $data){
        $data['updated_at']=time();
        $product_temp_id=$data['product_temp_id'];
        $size_name=$data['size_name'];
        $data['state']=1;
        $res=DB::table('product_temp_sizes')
            ->where(array('size_name'=>$size_name,'product_temp_id'=>$product_temp_id))
            ->update($data);
        return $res;
    }
    /***
     * 保存产品模板人群属性
     * @param array $data
     * @return mixed
     */
    private function saveProductTempAttribute(array $data){
        $data['created_at']=time();
        $data['updated_at']=time();
        $data['state']=1;
        return DB::table('product_temp_attr_maps')->insert($data);
    }

    /***
     * 更新产品模板属性
     * @param array $data
     * @return mixed
     */
    private function updateProductTempAttribute(array $data){
        $product_temp_id=$data['product_temp_id'];
        $attr_id=$data['attr_id'];
        $data['updated_at']=time();
        $data['state']=1;
        $res=DB::table('product_temp_attr_maps')
            ->where(array('attr_id'=>$attr_id,'product_temp_id'=>$product_temp_id))
            ->update($data);
        return $res;
    }

    /***
     * 删除模板属性
     * @param $product_temp_id
     * @return mixed
     */
    private function delProductTempAttribute($product_temp_id){
        $product_temp_id=trim($product_temp_id);
        if(empty($product_temp_id)){
            return false;
        }
        $res=DB::table('product_temp_attr_maps')
            ->where(array('product_temp_id'=>$product_temp_id))
            ->update(array('updated_at'=>time(),'state'=>0));
        return $res;
    }
    /***
     * 按产品模板名搜索产品模板(分页)
     * @param $request
     * @return mixed
     */
    public function searchProdTempList($search,$brand_id,$temp_category_id)
    {
        $product_temp_ids= DB::table('product_temps')
            ->where('name','like','%'.$search.'%')
            ->orWhere('product_temp_id','like','%'.$search.'%')
            ->pluck('product_temp_id')
            ->toArray();
        $query= DB::table('product_temps')->where('state',1)
            ->whereIn('product_temp_id',$product_temp_ids);
        if(!empty($brand_id)){
            $query->where('brand_id',$brand_id);
        }
        if(!empty($temp_category_id)){
            $query->where('product_temp_category_id',$temp_category_id);
        }
        $query->orderby('updated_at','DESC');
        $product_temps=$query->paginate(10);
        foreach ($product_temps as $product_temp){
            $brand_name=BrandToolService::getBrandNameByBrandId($product_temp->brand_id);
            $product_temp->brand_name=$brand_name;
        }
        $product_temps->appends(['search' => $search,'category_id' => $temp_category_id,'brand_id' => $brand_id])
            ->render();
        $product_temps->search = $search;
        return $product_temps;
    }
    public function searchProdTempSimpleList($search,$brand_id,$temp_category_id)
    {
        $product_temp_ids= DB::table('product_temps')
            ->where('name','like','%'.$search.'%')
            ->pluck('product_temp_id')
            ->toArray();
        $query= DB::table('product_temps')->where('state',1)
            ->whereIn('product_temp_id',$product_temp_ids);
        if(!empty($brand_id)){
            $query->where('brand_id',$brand_id);
        }
        if(!empty($temp_category_id)){
            $query->where('product_temp_category_id',$temp_category_id);
        }
        $query->select(
            'name as temp_name',
            'product_temp_id',
            'brand_id',
            'product_temp_category_id as category_id'
        );
        $query->orderby('updated_at','DESC');
        $product_temps=$query->get();
        foreach ($product_temps as $product_temp){
            $brand_name=BrandToolService::getBrandNameByBrandId($product_temp->brand_id);
            $product_temp->brand_name=$brand_name;
            $category_name=ProdTempCategoryTool::productTempCategoryNameByProdTempCategoryId($product_temp->category_id);
            $product_temp->category_name=$category_name;
        }
        return $product_temps;
    }
    /***
     * 按产品模板名搜索产品模板
     * @param $request
     * @return mixed
     */
    public function searchAllProdTempList($request)
    {
        $search = $request->input('search','');
        $product_temp_ids= DB::table('product_temps')
            ->where('name','like','%'.$search.'%')
            ->orWhere('product_temp_id','like','%'.$search.'%')
            ->pluck('product_temp_id')
            ->toArray();
        $product_temps= DB::table('product_temps')->where('state',1)
            ->whereIn('product_temp_id',$product_temp_ids)
            ->get()
            ->toArray();
        foreach ($product_temps as $product_temp){
            $brand_name=BrandToolService::getBrandNameByBrandId($product_temp->brand_id);
            $product_temp->brand_name=$brand_name;
        }
        return $product_temps;
    }

    /***
     * 获取单条产品模板主要信息
     * @param $product_temp_id
     * @return null
     */
    public function getProdTempByProdTempId($product_temp_id)
    {
        if(empty($product_temp_id)){
            return null;
        }
        $product_temp= DB::table('product_temps')->where('state',1)
            ->where('product_temp_id',$product_temp_id)
            ->first();
        if(!empty($product_temp)){
            $brand_name=BrandToolService::getBrandNameByBrandId($product_temp->brand_id);
            $product_temp->brand_name=$brand_name;
            $product_temp->category_name=ProdTempCategoryTool::productTempCategoryNameByProdTempCategoryId($product_temp->product_temp_category_id);
        }
        return $product_temp;
    }

    /***
     * 获取产品模板
     * @param $id
     * @return null
     */
    public function getProdTempById($id)
    {
        if(empty($id)){
            return null;
        }
        $product_temp= DB::table('product_temps')->where('state',1)
            ->where('id',$id)
            ->first();
        if(!empty($product_temp)){
            $brand_name=BrandToolService::getBrandNameByBrandId($product_temp->brand_id);
            $product_temp->brand_name=$brand_name;
        }
        return $product_temp;
    }
    /***
     * 删除模板
     * @param $product_temp_id
     * @return bool
     */
    public function delProdTempById($id)
    {
        if(empty($id)){
            return false;
        }
        $res= DB::table('product_temps')->where(array('state'=>1,'id'=>$id))
            ->update(array(
                'updated_at'=>time(),
                'state'=>0,
            ));
        return ($res==1)?true:false;
    }

    /***
     * 产品模板id删除产品模板
     * @param $id
     * @return bool
     */
    public function delProdTempByProdTempId($product_temp_id)
    {
        try{
            DB::beginTransaction();
            if(empty($product_temp_id)){
                return false;
            }
            //删除和某一模板相关的数据
            $this->delProductTempCrowdsByProductTempId($product_temp_id);
            $this->delProductTempSizesByProductTempId($product_temp_id);
            $this->delProductTempAttrMapsByProductTempId($product_temp_id);
            $this->delProductTempColour($product_temp_id);
            $this->delProductTempStocksByProductTempId($product_temp_id);//删除库存
            //解除模板和标签之间的映射
            TagTool::delResourceInTagsByResourceId($product_temp_id,2);
            $res= DB::table('product_temps')->where(array('state'=>1,'product_temp_id'=>$product_temp_id))
                ->update(array(
                    'updated_at'=>time(),
                    'state'=>0,
                ));
            return ($res>0)?true:false;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 添加创作区域模板
     * @param array $data
     * @param $type 1添加 2更新
     * @return bool
     */
    public function addCustomZone(array $data,$type){
        try{
            $image=$data['image'];
            $colour_id=$data['colour_id'];
            $product_temp_id=$data['product_temp_id'];
            $position_type=$data['position_type'];
            unset($data['image']);
            unset($data['colour_id']);
            $product_temp_colour_id=DB::table('product_temp_colours')
                ->where(array('product_temp_id'=>$product_temp_id,'colour_id'=>$colour_id,'state'=>1))
                ->value('id');
            if(empty($product_temp_colour_id)){
                return false;
            }
            if(!empty($image)){
                $img_path=$this->imgTool->imgSave($image,2);
            }
            if(($type===1)&&empty($img_path)){
                return false;
            }
            if(!empty($img_path)){
                $data['original_image']=$img_path;
                $image_thumbnail_url=$this->imgTool->getImgThumbByImgPath($img_path,600,600,true);
                $data['thumbnail']=$image_thumbnail_url;
            }
            $num=DB::table('product_temp_custom_zones')
                ->where(array(
                'product_temp_id'=>$product_temp_id,
                'position_type'=>$position_type,
                'prod_temp_colour_id'=>$product_temp_colour_id
            ))->count();
            DB::beginTransaction();
            $time=time();
            $data['updated_at']=$time;
            $data['state']=1;
            if($num!==0){
                $res=DB::table('product_temp_custom_zones')->where(array(
                    'product_temp_id'=>$product_temp_id,
                    'position_type'=>$position_type,
                    'prod_temp_colour_id'=>$product_temp_colour_id
                ))->update($data);
            }else{
                $data['created_at']=$time;
                $data['prod_temp_colour_id']=$product_temp_colour_id;
                $res=DB::table('product_temp_custom_zones')->insert($data);
            }
            return ($res==0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 获取size_list里面字段数
     * @param $product_temp_id
     * @param int $state
     * @return int
     */
    public function getProductTempSizeFormatSizeKeyNum($product_temp_id,$state=1){
        if(empty($product_temp_id)){
            return 0;
        }
        $query=DB::table('product_temp_size_formats')->where(array('product_temp_id'=>$product_temp_id));
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->value('size_key_num');
        return empty($num)?0:$num;
    }
    /***
     * 更新产品模板尺码格式
     * @param array $data
     * @return bool
     */
    public function updateProductTempSizeFormat(array  $data){
        try{
            $image=$data['measure_method_image'];
            unset($data['measure_method_image']);
            $size_list=$data['size_list'];
            $size_arr=explode('|',$size_list);
            $size_arr=array_filter($size_arr);
            $data['size_key_num']=sizeof($size_arr);
            $id=DB::table('product_temp_size_formats')
                ->where(array('product_temp_id'=>$data['product_temp_id']))
                ->value('id');
            if(!empty($image)){
                $img_path=$this->imgTool->imgSave($image,2);
                if (!empty($img_path)){
                    $data['measure_method_image']=$img_path;
                }
            }
            DB::beginTransaction();
            $time=time();
            $data['updated_at']=$time;
            $data['state']=1;
            if(!empty($id)){
                $res=DB::table('product_temp_size_formats')->where(array(
                    'id'=>$id,
                ))->update($data);
            }else{
                $data['created_at']=$time;
                $res=DB::table('product_temp_size_formats')->insert($data);
            }

            return ($res==0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 更新产品模板尺码详情
     * @param $id
     * @param $size_values
     * @return bool
     */
    public function updateProductTempSizeValues($id,$size_values){
        try{
            $res=DB::table('product_temp_sizes')->where(array(
                'id'=>$id,
            ))->update(array(
                'size_values'=>$size_values,
                'updated_at'=>time(),
            ));
            return ($res==0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 获取产品模板标签列表
     * @param array $data
     * @return bool|null
     */
    public function getProductTempTagList(array $data){
        $per_page=(!isset($data['per_page'])||!is_int($data['per_page']))?10:$data['per_page'];
        $data['per_page']=$per_page;
        $where_arr=array();
        $where_arr['app_id']=2;
        $data['where']=$where_arr;
        $data['orderByKeyword']='sort';
        $data['orderByRule']='ASC';
        $tags=TagTool::pagedAccessToTags($data);
        if (empty($tags)){
            return false;
        }
        foreach ($tags as $tag){
            $tag->has_sub_tag=TagTool::hasSubTagByTagId($tag->id,1);
        }
        return $tags;
    }

    /***
     * 批量更新产品模板
     * @param array $data
     * @return bool
     */
    public function bachUpdateProductTemp(array $data){
        try{
            $type=$data['type'];//当前只是批量修改产品模板标签，后面应该按照类型分别处理操作
            $type_value=$data['type_value'];
            $data_arr=$data['data_arr'];
            $tag_exist=TagTool::tagExistByTagId($type_value,1);
            if(!is_array($data_arr)){
                return false;
            }
            DB::beginTransaction();
            if($tag_exist){
                foreach ($data_arr as $resource_id){
                    $resource['tag_id']=$type_value;
                    $resource['resource_id']=$resource_id;
                    $resource['app_id']=2;
                    TagTool::saveTagResourceMaps($resource);
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 更新产品模板排序
     * @param $product_temp_id
     * @param $sort
     * @return bool
     */
    public function updateProductTempSort($product_temp_id,$sort){
        if(empty($product_temp_id)||(!is_int($sort))||($sort<0)){
            return false;
        }
        $update_res=  DB::table('product_temps')->where(array('state'=>1,'product_temp_id'=>$product_temp_id))
            ->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return ($update_res===1)?true:false;
    }

    /****
     *  更新指定区域排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public function updateCustomZoneSort($id,$sort){
        if(empty($id)||(!is_int($sort))||($sort<0)){
            return false;
        }
        $update_res=  DB::table('product_temp_custom_zones')->where(array('state'=>1,'id'=>$id))
            ->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return ($update_res===1)?true:false;
    }

    /***
     * 更新定制区域排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public function updateCraftsmanshipSort($id,$sort){
        if(empty($id)||(!is_int($sort))||($sort<0)){
            return false;
        }
        $update_res=  DB::table('product_temp_craftsmanships')->where(array('state'=>1,'id'=>$id))
            ->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return ($update_res===1)?true:false;
    }
    /***
     * 获取标签下的产品模板列表，分页
     * @param $tag_id
     * @return bool
     */
    public function getProductTempByTagId($tag_id)
    {
        if(empty($tag_id)||!is_int($tag_id)){
            return false;
        }
        $product_temp_ids=DB::table('product_temps')
            ->where('state',1)
            ->pluck('product_temp_id')
            ->toArray();
        $query= DB::table('tag_resource_maps')->where(array('state'=>1,'app_id'=>2));
        $query->where('tag_id',$tag_id);
        $query->whereIn('resource_id',$product_temp_ids);
        $query->orderby('sort','ASC');
        $product_temp_ids=$query->select(
            'id as tag_resource_map_id',
            'updated_at',
            'sort',
            'resource_id as product_temp_id'
        )->paginate(10);
        $product_temp_ids->appends(['id' => $tag_id])->render();
        return $product_temp_ids;
    }

    /***
     *  删除产品模板属性
     * @param $attr_id
     * @return bool
     */
    public function deleteProductTempAttr($attr_id){
        if(empty($attr_id)||!is_int($attr_id)){
            return false;
        }
        $res=DB::table('product_temp_attributes')
            ->where(array(
            'attr_id'=>$attr_id,
            'state'=>1,
        ))->update(array(
          'updated_at'=>time(),
          'state'=>0,
        ));
        return ($res==0)?false:true;
    }

    /***
     * 更新模板属性类型值
     * @param $attr_id
     * @param $attr_values
     * @return bool
     */
    public function updateTempAttrValues($attr_id,$attr_values){
        if(empty($attr_id)||!is_int($attr_id)){
            return false;
        }
        $res=DB::table('product_temp_attributes')
            ->where(array(
                'attr_id'=>$attr_id,
                'state'=>1,
            ))->update(array(
                'updated_at'=>time(),
                'attr_values'=>$attr_values,
                'state'=>1,
            ));
        return ($res==0)?false:true;
    }
    /***
     * id删除标签产品模板绑定
     * @param $tag_resource_map_id
     * @return bool
     */
    public function deleteTagTempMap($tag_resource_map_id){
        if(empty($tag_resource_map_id)||!is_int($tag_resource_map_id)){
            return false;
        }
        $res=$this->tagService->deleteTagTempMapById($tag_resource_map_id);
        return $res;
    }

    /****
     * 添加产品模板资源绑定
     * @param array $data
     * @return bool
     */
    public function addTagTempMap(array $data){
        try{
            $tag_id=$data['tag_id'];
            $resource_id=$data['resource_id'];
            $data['updated_at']=time();
            $data['state']=1;
            $data['app_id']=2;
            $exist=TagTool::resourceIdHasBindingTagId($tag_id,2,$resource_id,0);
            if($exist){
                $query=DB::table('tag_resource_maps')
                    ->where(array('tag_id'=>$tag_id,'resource_id'=>$resource_id));
                $num=$query->update($data);
            }else{
                $data['created_at']=time();
                $num=DB::table('tag_resource_maps')->insert($data);
            }
            return empty($num)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 获取定制区域下可选择颜色
     * @param $temp_craftsmanship_id
     * @return mixed
     */
    public function getProductTempCraftsmanshipColours($temp_craftsmanship_id){
        if(empty($temp_craftsmanship_id)){
            $temp_craftsmanship_id=0;
        }
        $temp_craftsmanship_colours=DB::table('product_temp_craftsmanship_colours')
            ->where(array('product_temp_craftsmanship_id'=>$temp_craftsmanship_id,'state'=>1))
            ->select('id','product_temp_craftsmanship_id','colour_id','sort')
            ->paginate(10);
        return $temp_craftsmanship_colours;
    }

    /***
     * 添加定制区域工艺对应颜色
     * @param $data
     * @return bool
     */
    public function addCraftsmanshipColour($data){
        try{
            if(!isset($data['colour_id'])||!isset($data['product_temp_craftsmanship_id'])){
                return false;
            }
            $colour_id=$data['colour_id'];
            $product_temp_craftsmanship_id=$data['product_temp_craftsmanship_id'];
            $product_temp_craftsmanship_exist=ProductTempTool::productTempCraftsmanshipColourExistByCraftsmanshipIdAndColourId($product_temp_craftsmanship_id,$colour_id,0);
            if($product_temp_craftsmanship_exist){
               $res=$this->updateTempCraftsmanshipColour($data);
            }else{
                $res=$this->saveTempCraftsmanshipColour($data);
            }
            return $res;
        }catch (\Exception $e){
        Log::info($e);
        return false;
        }
    }

    /****
     * 添加制作工艺默认颜色
     * @param $data
     * @return bool
     */
    public function addCraftsmanshipDefaultColour($data){
        try{
            if(!isset($data['colour_id'])){
                return false;
            }
            $colour_id=$data['colour_id'];
            $colour_id_exist=$this->productTempTool->craftsmanshipDefaultColourIdExistByColourId($colour_id,0);
            if($colour_id_exist){
                $res=$this->updateTempCraftsmanshipDefaultColour($data);
            }else{
                $res=$this->saveTempCraftsmanshipDefaultColour($data);
            }
            return $res;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 保存定制区域工艺对应颜色
     * @param $data
     * @return bool
     */
    public function saveTempCraftsmanshipColour($data){
        try{
            if(!isset($data['colour_id'])||!isset($data['product_temp_craftsmanship_id'])){
                return false;
            }
            $data['created_at']=time();
            $data['updated_at']=time();
            $data['state']=1;
            $res=DB::table('product_temp_craftsmanship_colours')->insert($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::ifno($e);
            return false;
        }
    }

    /****
     * 保存制作工艺默认颜色
     * @param $data
     * @return bool
     */
    public function saveTempCraftsmanshipDefaultColour($data){
        try{
            if(!isset($data['colour_id'])){
                return false;
            }
            $data['created_at']=time();
            $data['state']=1;
            $res=DB::table('product_temp_craftsmanship_default_colours')->insert($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 更新定制区域工艺对应颜色
     * @param $data
     * @return bool
     */
    public function updateTempCraftsmanshipColour($data){
        try{
            if(!isset($data['colour_id'])||!isset($data['product_temp_craftsmanship_id'])){
                return false;
            }
            $data['updated_at']=time();
            $data['state']=1;
            $colour_id=$data['colour_id'];
            $product_temp_craftsmanship_id=$data['product_temp_craftsmanship_id'];
            $res=DB::table('product_temp_craftsmanship_colours')
                ->where(array(
                    'colour_id'=>$colour_id,
                    'product_temp_craftsmanship_id'=>$product_temp_craftsmanship_id
                ))->update($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 更新制作工艺默认颜色
     * @param $data
     * @return bool
     */
    public function updateTempCraftsmanshipDefaultColour($data){
        try{
            if(!isset($data['colour_id'])){
                return false;
            }
            $data['state']=1;
            $colour_id=$data['colour_id'];
            $res=DB::table('product_temp_craftsmanship_default_colours')
                ->where(array(
                    'colour_id'=>$colour_id,
                ))->update($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 保存产品模板属性
     * @param array $data
     * @return bool
     */
    public function addTempAttr(array  $data){
        try{
            $data['created_at']=time();
            $data['updated_at']=time();
            $data['state']=1;
            $res=DB::table('product_temp_attributes')->insert($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 更新产品模板属性
     * @param array $data
     * @return bool
     */
    public function updateTempAttr(array  $data){
        try{
            $id=$data['attr_id'];
            $data['updated_at']=time();
            $data['state']=1;
            $res=DB::table('product_temp_attributes')->where(array('attr_id'=>$id))->update($data);
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * excel导出产品模板库存
     * @param array $temp_ids
     * @return array|bool
     */
    public  function exportStockExcelByTempIds(array $temp_ids){
       try{
           $query =DB::table('product_temp_stocks')->where('state',1);
           $query->whereIn('product_temp_id',$temp_ids);
           $query->select(
               'id',
               'product_temp_id',
               'colour_id',
               'colour_name',
               'size_name',
               'sku',
               'stock',
               'actual_stock'
           );
           $query->orderBy('id');
           $temp_stocks=$query->get();
           foreach ($temp_stocks as $temp_stock){
               $temp_name=$this->productTempTool->getProductTempNameByProductTempId($temp_stock->product_temp_id);
               $temp_stock->temp_name=$temp_name;
               $category_name=$this->productTempTool->getCategoryNameByTempId($temp_stock->product_temp_id);
               $temp_stock->category_name=$category_name;
           }
           $rows=array();
           foreach($temp_stocks as $temp_stock){
            $arr=array(
                "编号"=>$temp_stock->id,
                "分类"=>$temp_stock->category_name,
                "模板编号"=>$temp_stock->product_temp_id,
                "模板名称"=>$temp_stock->temp_name,
                "颜色编号"=>$temp_stock->colour_id,
                "颜色"=>$temp_stock->colour_name,
                "尺码"=>$temp_stock->size_name,
                "SKU"=>$temp_stock->sku,
                "虚拟库存"=>empty($temp_stock->stock)?0:$temp_stock->stock,
                "实际库存"=>empty($temp_stock->actual_stock)?0:$temp_stock->actual_stock,
            );
            $rows[]=$arr;
           }
           $excel_name='temp_stock_'.time();
           $excel_folder='excel'.DIRECTORY_SEPARATOR.date('Ym').DIRECTORY_SEPARATOR;
           Excel::create($excel_name, function($excel) use ($rows) {
               $excel->sheet('temp_stock', function($sheet) use ($rows) {
                   $sheet->fromArray($rows);
               });
           })->store('xls', public_path($excel_folder));
           $get_xls_url=asset($excel_folder.$excel_name.".xls");
           return $get_xls_url;
       }catch (\Exception $e){
           Log::info($e);
           return false;
       }

    }
    public function stockImport(array $data){
        try{
            $excel_file=$data['excel'];
            $ext=$excel_file->getClientOriginalExtension();
            $is_excel=in_array($ext,self::EXCEL_EXT);
            if(!$is_excel){
                return array('state'=>-2,'message'=>'文件不是excel');
            }
            $excel_name='excel_'.time().'.'.$ext;
            $excel_folder='excel'.DIRECTORY_SEPARATOR.date('Ym').DIRECTORY_SEPARATOR;
            @$this->tool->mkFolder($excel_folder);
            $excel_absolute_folder=public_path($excel_folder);
            $excel_file->move($excel_absolute_folder,$excel_name);
            $excel_absolute_path=$excel_absolute_folder.$excel_name;
            if(!file_exists($excel_absolute_path)){
                return array('state'=>-3,'message'=>'保存文件失败');
            }
            Excel::load($excel_absolute_path, function($reader) use( &$res ) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });
            DB::beginTransaction();
            foreach ($res as $re){
                if(empty($re)) continue;
                if(!is_array($re)||(sizeof($re)<10)) continue;
                $data=array();
                $data['product_temp_id']=empty($re[2])?'':$re[2];
                $data['colour_id']=empty($re[4])?'':$re[4];
                $data['colour_name']=empty($re[5])?'':$re[5];
                $data['size_name']=empty($re[6])?'':$re[6];
                $data['stock']=empty($re[8])?0:$re[8];
                $data['actual_stock']=empty($re[9])?0:$re[9];
                $this->stockImportUpdateStock($data);
            }
            return array('state'=>1,'message'=>'更新成功');
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 导入库存列表时，更新库存信息
     * @param array $stock
     * @return bool
     */
    private function stockImportUpdateStock(array  $stock){
        $product_temp_id=$stock['product_temp_id'];
        $colour_id=$stock['colour_id'];
        $colour_name=$stock['colour_name'];
        $size_name=$stock['size_name'];
        if(empty($product_temp_id)
         ||empty($colour_id)
         ||empty($colour_name)
         ||empty($size_name))
        {
            return false;
        }
        $res=DB::table('product_temp_stocks')->where(array(
            'product_temp_id'=>$product_temp_id,
            'colour_id'=>$colour_id,
            'colour_name'=>$colour_name,
            'size_name'=>$size_name,
        ))->update($stock);
        return ($res>0)?true:false;
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public static function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }

    /****
     * 获取定制区域默认颜色列表
     * @param Request $request
     * @return mixed
     */
    public  function getCraftsmanshipDefaultColourList(Request $request)
    {
        $query= DB::table('product_temp_craftsmanship_default_colours');
        $query->where('state',1);
        $default_colours=$query->paginate(10);
        foreach ($default_colours as $default_colour){
            $colour_name="";
            $colour_id="";
            $colour_code="";
            $colour_image="";
            if(!empty($default_colour->colour_id)){
                $colour=ColourTool::getColourByColourId($default_colour->colour_id);
                if(!empty($colour)){
                    $colour_name=$colour->colour_name;
                    $colour_id=$colour->colour_id;
                    $colour_code=$colour->colour_code;
                    $colour_image=$colour->colour_image;
                }
                $default_colour->colour_name=$colour_name;
                $default_colour->colour_id=$colour_id;
                $default_colour->colour_code=$colour_code;
                $default_colour->colour_image=$colour_image;
            }
        }
        return $default_colours;
    }
}